import java.util.HashMap;
import java.util.Stack;

public class NextGreaterElement {

    public int[] nextGreaterElement(int[] nums1, int[] nums2) {
        HashMap<Integer, Integer> map = new HashMap<>();
        int[] temp = new int[nums2.length];
        for (int i = 0; i < temp.length; i++) {
            temp[i] = -1;
        }
        Stack<Integer> stack = new Stack<>();
        for (int i = 0; i < nums2.length; i++) {
            while (!stack.isEmpty() && nums2[stack.peek()] < nums2[i]) {
                Integer j = stack.pop();
                temp[j] = i;
            }
            stack.push(i);
            map.put(nums2[i], i);
        }
        int[] ans = new int[nums1.length];
        for (int i = 0; i < nums1.length; i++) {
            Integer j = map.get(nums1[i]);
            if (temp[j] == -1) {
                ans[i] = -1;
            } else ans[i] = nums2[temp[j]];
        }
        return ans;
    }
}
